package com.controladores.controlvehicular;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.net.Socket;
import java.net.UnknownHostException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends Activity {
	protected TextView fuenteIU;
	protected TextView fuenteIC;
	protected TextView fuenteSM;
	protected TextView fuenteER;
	private EditText texto;
	private TextView salidaTxt;
	private TextView contador;
	private Button btnEnviar;
	Socket sk;
	DataInputStream entrada;

	public DataInputStream getEntrada() {
		return entrada;
	}

	public void setEntrada(DataInputStream entrada) {
		this.entrada = entrada;
	}

	DataOutputStream salida;

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	String msg = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		texto = (EditText) findViewById(R.id.editText1);
		salidaTxt = (TextView) findViewById(R.id.textView1);
		contador = (TextView) findViewById(R.id.textView2);

		// Creamos la Base de datos
		// crearBBDD();
		GestorBaseDatos miGestor = new GestorBaseDatos(MainActivity.this);
		try {
			miGestor.crearDataBase();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		miGestor.abrirBaseDatos();
		miGestor.close();

		ImageButton botonIL = (ImageButton) findViewById(R.id.ibtn);
		botonIL.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Log.v(getClass().getCanonicalName(), "Iniciando Socket...");
				Log("Enviando... " + texto.getText().toString() + "\n");
				try {
					ejecutaClienteSocket();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				Intent aZona = new Intent(MainActivity.this, Zona.class);
				startActivity(aZona);
			}
		});
		fuenteIU = (TextView) findViewById(R.id.etIU);
		Typeface tipofuente = Typeface.createFromAsset(getAssets(),
				"gloriahallelujah.ttf");
		fuenteIU.setTypeface(tipofuente);

		fuenteIC = (TextView) findViewById(R.id.etIC);
		fuenteIC.setTypeface(tipofuente);

		fuenteSM = (TextView) findViewById(R.id.etSMfuente);
		Typeface tipofuenteT = Typeface.createFromAsset(getAssets(),
				"AdventPsychosis.ttf");
		fuenteSM.setTypeface(tipofuenteT);

		fuenteER = (TextView) findViewById(R.id.etER);
		fuenteER.setTypeface(tipofuenteT);

		String ip = "192.168.1.6";
		int puerto = 3031;
		Log.v(this.getClass().getClass().getCanonicalName(), "Socket " + ip
				+ " " + puerto);
		try {
			sk = new Socket(ip, puerto);
			Log.v(getClass().getCanonicalName(), "Se ha iniciado conexion...");
			Log("Conexion con servidor: " + ip + " Puerto: " + puerto);
			entrada = new DataInputStream(new BufferedInputStream(
					sk.getInputStream()));
			salida = new DataOutputStream(new BufferedOutputStream(
					sk.getOutputStream()));

		} catch (UnknownHostException e) {
			e.printStackTrace();
			salidaTxt.append(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			salidaTxt.append(e.getMessage());
		}

		// ---------------------------------------------------------------
		final Handler myHandler = new Handler();

		(new Thread(new Runnable() {

			public void run() {
				while (true) {

					String recibe;
					try {
						recibe = getEntrada().readUTF();
						if (recibe != null) {
							MainActivity.this.setMsg(recibe);
							Log.v(getClass().getCanonicalName(),
									"Recibiendo datos.." + recibe);
						}

					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					myHandler.post(new Runnable() {
						public void run() {
							actualizarMensajes();
						}
					});
				}
			}
		})).start();

		// ---------------------------------------------------------------
		Log.v(getClass().getCanonicalName(),
				"Terminando de iniciar componentes");
	}

	// crear la base de datos en basedatos helper
	GestorBaseDatos miBBDDHelper;

	/*
	 * public void crearBBDD() { miBBDDHelper = new GestorBaseDatos(this); try {
	 * miBBDDHelper.crearDataBase(); } catch (IOException ioe) { throw new
	 * Error("Unable to create database"); } }
	 */

	private void CopyDB(InputStream open, OutputStream exit) throws IOException {
		// TODO Auto-generated method stub
		byte[] buffer = new byte[1024];
		int length;
		while ((length = open.read(buffer)) > 0) {
			exit.write(buffer, 0, length);
		}
		open.close();
		exit.close();
	}

	private void ejecutaClienteSocket() throws IOException {
		try {
			Log.v(getClass().getCanonicalName(), "Enviando datos..."
					+ texto.getText().toString());
			salida.writeUTF(texto.getText().toString());
			salida.flush();
		} catch (Exception e) {
			Log.v(this.getClass().getClass().getCanonicalName(), e.getMessage());
		}
		// Recibe datos de respuesta del servidor
		try {
			String recibe = entrada.readUTF();
			Log("Recibiendo... " + recibe);
			Log.v(getClass().getCanonicalName(), "Recibiendo datos.." + recibe);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		try {
			sk.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	static int val = 0;

	protected void Log(String dato) {
		Log.v("Enviando a log valor: " + val, dato);
		salidaTxt.append(dato + "\n");
		val = val + 1;
	}

	static int cont = 0;

	private void delay(long tiempo) {
		try {
			Thread.sleep(tiempo);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void actualizaContador() {
		cont = cont + 1;
		contador.setText(Integer.toString(cont));
	}

	private void actualizarMensajes() {
		this.Log(getMsg());
	}
}
